
# V1.1.1
# 2021-1-6
# 重写了 get_music，play_music
# 摒弃 ConnectionError_deal
# 采用 recode_log，test_music
# 对异常捕捉做出优化
# 修复输出编码异常

# V1.1.2
# 2021-1-13
# 新添加一个接口
# 调整异常后换接口运行

import requests
import mp3play
import time
M_data_path='./M_data/'
class MY_Music():
    def __init__(self):
        self.Apis=['https://api.uomg.com/api/rand.music?sort=%E7%83%AD%E6%AD%8C%E6%A6%9C&format=json','https://api.66mz8.com/api/rand.music.163.php?format=json']
        self.C_Api=self.Apis.copy()
        self.api=self.Apis[0]
        self.tag=True
        while self.tag:
            self.tag=self.get_music()
            self.play_music()
    def get_music(self):
        Tag,index=self.test_music()
        if Tag:
            json_music=self.ret.json()
            if index==0:
                    self.music_data={'name':json_music['data']['name'],
                                 'pic':json_music['data']['picurl'],
                                 'artistsname':json_music['data']['artistsname'],
                                 'music':self.url_music
                                }
            elif index==1:
                    self.music_data={'name':json_music['name'],
                                 'pic':json_music['music_pic'],
                                 'artistsname':json_music['artists_name'],
                                 'music':self.url_music
                                }
            else:
                    self.music_data=None
            return True
        else:
            return False
    def play_music(self):
        if self.tag:
            mp3=mp3play.load(self.music_data['music'])
            self.recode_data()
            mp3.play()
            print(self.music_data['name']+'   正在播放中~~~')
            time.sleep(mp3.seconds()+3)
            # time.sleep(10)
            mp3.stop()
    def ConnectionError_deal(self):
        i=0
        head={    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36'}
        for i in range(5):
            try:
                print('网络连接错误，正在第{0}次重试...'.format(i+1))
                self.ret=requests.get(self.api,headers=head)
            except BaseException as e:
                time.sleep(3)
            else:
                with open(M_data_path+'log.txt', 'a')as f:
                    f.write('\n'+time.strftime('%Y-%m-%d %H:%M:%S')+'网络发生错误，第{0}次重连成功！'.format(i+1))
                print('第{0}次重连成功！'.format(i+1))
                break
        if i==4:
            return 0
        else:
            return 1
    def recode_data(self):
        with open(M_data_path+'Music_data.txt', 'a', encoding='utf-8') as f:
            now_time=time.strftime('%Y-%m-%d %H:%M:%S')
            recode_data=['时间:'+now_time+'\n',
                         'name:'+self.music_data['name']+'\n',
                         '图片:'+self.music_data['pic']+'\n',
                         '歌手:'+self.music_data['artistsname']+'\n',
                         '歌曲地址:'+self.music_data['music']+'\n',
                         '--------------------------------------------------------------------------------\n'
                         '--------------------------------------------------------------------------------\n'
                         ]
            f.writelines(recode_data)
            f.close()
    def test_music(self):
        head={    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36'}
        for url in self.C_Api:
            try:
                self.ret=requests.get(url,headers=head)
                json_music=self.ret.json()

                if self.Apis.index(url)==0:
                    file=json_music['data']['url']
                elif self.Apis.index(url)==1:
                    file=json_music['music_url']
                else:
                    file=None  #添加接口所加的位置

                self.url_music=requests.get(file,headers=head).url
                mp3play.load(self.url_music)
            except BaseException as e:
                print(str(e))
                for i in range(1,6):
                    try:
                        self.ret=requests.get(url,headers=head)
                        json_music=self.ret.json()
                        if self.Apis.index(url)==0:
                            file=json_music['data']['url']
                        elif self.Apis.index(url)==1:
                            file=json_music['music_url']
                        else:
                            file=None  #添加接口所加的位置
                        self.url_music=requests.get(file,headers=head).url
                        mp3play.load(self.url_music)
                    except BaseException as r:
                        print('第{0}次重试，请稍后...'.format(i))
                    else:
                        print('第{0}次重试成功！'.format(i))
                        self.recode_log('第{0}次重试成功！,可以正常使用。\n问题来源:{1}'.format(i,str(e)))
                        return (True,self.Apis.index(url))
                    time.sleep(3)
                if url==self.C_Api[-1]:
                    print('程序无法自动修复，正在退出程序！\n最终问题来源：{1}'.format(url,str(e)))
                    self.recode_log('程序无法自动修复，正在退出程序！\n最终问题来源：{1}'.format(url,str(e)))
                else:
                    print('API:{0}\n程序无法自动修复，正在换其他源！\n问题来源：{1}'.format(url,str(e)))
                    self.recode_log('API:{0}\n程序无法自动修复，正在换其他！\n问题来源：{1}'.format(url,str(e)))
            else:
                self.C_Api.remove(url)
                self.C_Api.insert(0,url)
                return (True,self.Apis.index(url))
        return (False,None)
    def recode_log(self,error):
        current_time=time.strftime('%Y-%m-%d %H:%M:%S')
        with open(M_data_path+'log.txt', 'a', encoding='utf-8')as f:
            f.write(current_time+'-'+error+'\n--------------------------------------------------------------------------------\n'
                                           '--------------------------------------------------------------------------------\n')

if __name__=='__main__':
    MY_Music()




